/**
 * Copyright 2020 jianggujin (www.jianggujin.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jianggujin.dbfly.mybatis.version;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;

import com.jianggujin.dbfly.mybatis.entity.JEntity;
import com.jianggujin.dbfly.mybatis.entity.JEntityColumn;
import com.jianggujin.dbfly.mybatis.entity.JEntityResolver;
import com.jianggujin.dbfly.util.JDBFlyException;

/**
 * 版本号生成工具
 * 
 * @author jianggujin
 *
 */
public class JVersionGeneratorUtils {

    private static final Map<Class<? extends JVersionGenerator>, JVersionGenerator> CACHE = new ConcurrentHashMap<Class<? extends JVersionGenerator>, JVersionGenerator>();

    private static final ReentrantLock LOCK = new ReentrantLock();

    /**
     * 生成版本号
     *
     * @param entityClass
     * @param property
     * @param current
     * @throws JDBFlyException
     */
    public static void generateVersion(Class<?> entityClass, String property, Object current) throws JDBFlyException {
        JEntity entity = JEntityResolver.getEntity(entityClass);
        JEntityColumn column = entity.getColumn(property);
        if (column == null) {
            return;
        }
        Class<? extends JVersionGenerator> versionGeneratorClass = column.getVersionGeneratorClass();
        try {
            JVersionGenerator versionGenerator;
            if (CACHE.containsKey(versionGeneratorClass)) {
                versionGenerator = CACHE.get(versionGeneratorClass);
            } else {
                LOCK.lock();
                try {
                    if (!CACHE.containsKey(versionGeneratorClass)) {
                        CACHE.put(versionGeneratorClass, versionGeneratorClass.newInstance());
                    }
                    versionGenerator = CACHE.get(versionGeneratorClass);
                } finally {
                    LOCK.unlock();
                }
            }
            versionGenerator.generateVersion(entity, column, current);
        } catch (Exception e) {
            throw new JDBFlyException("生成Version失败", e);
        }
    }

}
